// 解析 URL 参数
function getUrlParams() {
    const searchParams = new URLSearchParams(window.location.search);
    const params = {};
    for (const [key, value] of searchParams.entries()) {
        params[key] = value;
    }
    return params;
}

async function convertImageToBase64(url) {
    const response = await fetch(url);
    const blob = await response.blob();
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            const base64data = reader.result;
            resolve(base64data);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
    });
}

function postData(event) {
    event.preventDefault();
    const formElement = document.getElementById("mainform"); // 通过表单的 ID 获取表单元素
    // 使用FormData对象来获取表单的数据
    const formData = new FormData(formElement);
    // 将FormData对象转换为对象字面量
    const formDataObject = {};
    formData.forEach(function (value, key) {
        formDataObject[key] = value;
    });
    formDataObject["EDIT_TYPE"] = "ADD"; //处理方式为新增
    formDataObject["base"] = formDataObject["base"].replaceAll("\r\n", "\n").replaceAll("\n", "#0D0A");
    formDataObject["PICTUREURL"] = document.getElementById("item_pic_url").src;
    var season = formDataObject["season"];
    if (season != null && season.length > 1) {
        formDataObject["season"] = "";
    }
    // 输出JSON字符串
    $.ajax({
        url: properties.postURL, //发起接口调用
        method: "POST",
        contentType: "application/x-www-form-urlencoded",
        data: formDataObject,
        success: function (response) {
            // 请求成功时的处理
            const { code, msg, message } = JSON.parse(response);
            if (code !== 200) {
                alert(msg || message, "error");
            } else {
                alert("提交处理成功!", "success");
                setTimeout(() => {
                    // 关闭当前弹出界面
                    window.close();
                }, 500);
            }
        },
        error: function (xhr, status, error) {
            // 请求出错时的处理
            console.log(error);
        },
    });
}

$(function () {
    const params = getUrlParams();
    //转JSON对象，并给表单赋值
    const content = JSON.parse(params.data);
    //设置表单内容
    document.getElementById("item_name").value = content.title || "";
    document.getElementById("item_style").value = content.style || "";
    document.getElementById("item_shop").value = content.shop || "";
    document.getElementById("item_saleYear").value = content.year || "";
    document.getElementById("item_saleDesc").value = content.saleDesc;
    document.getElementById("item_seasonDesc").value = content.season || "";
    document.getElementById("item_price").value = content.price || "";
    document.getElementById("item_searchTime").value = new Date().toLocaleString();
    document.getElementById("item_base").value = content.base.join("\r\n");
    document.getElementById("item_platform").value = content.platform;
    document.getElementById("from_source").innerText = content.platform;
    document.getElementById("item_link").value = content.url;
    //document.getElementById("item_user").value = content.uname || "";
    document.getElementById("item_uid").value = content.uid || "";
    document.getElementById("item_size").value = content.size || "";
    document.getElementById("item_color").value = content.color || "";
    if (content.gender) {
        document.getElementById("item_gender").value = content.gender;
    }
    //加载找款人
    const formData = {
        pageId: "PG-B1E5-D617-EA134433",
        compId: "com.pucheng.fastfashion.productlist.getAllDutyUser",
        params: "{}"
    };
    $.ajax({
        url: "http://" + properties.scmURL + "/gdpaas/jscomp/run.htm", // 替换为你的接口地址
        method: "POST",
        contentType: "application/x-www-form-urlencoded",
        data: formData,
        success: function (result) {
            var selectpicker = $("#item_user");
            const {code, msg, data} = JSON.parse(result).data;
            if(code == 200) {
                data.forEach(function (item) {
                    selectpicker.append("<option value='" + item.USER_NAME +"'>" + item.USER_NAME + "</option>");
                });
                document.getElementById("item_user").value = content.uname || "";
                // 刷新 Bootstrap Select 组件来显示新的选项
                // selectpicker.selectpicker("refresh");
                $('#item_user').on('change', function(event) {
                    var value = event.target.value;
                    if(value != '') {
                        var find = data.find(item => item.USER_NAME == value);
                        if(find) {
                            document.getElementById("item_uid").value = find.USER_ID;
                        }
                    }
                    //var selectedOption = $(this).find('option').eq(clickedIndex).text();
                    //console.log('Selected option: ', selectedOption);
                });
            } else {
                alert(msg);
            }
        },
        error: function (err) {
            console.error("Error fetching data");
        },
    });

    var imageUrls = content.imageUrls;
    // 获取图片容器
    var imageContainer = document.getElementById("scroll-content");
    // 遍历图片URL数组，创建并添加<img>标签
    if (imageUrls) {
        for (var i = 0; i < imageUrls.length; i++) {
            var img = document.createElement("img");
            img.src = imageUrls[i];
            img.width = 100;
            img.height = 100;
            img.style.marginTop = "10px";
            img.style.marginBottom = "10px";
            if (i != imageUrls.length - 1) {
                img.style.marginRight = "5px";
            }
            imageContainer.appendChild(img);
            img.addEventListener("click", function () {
                // 在这里编写处理图片点击事件的代码
                (async () => {
                    try {
                        var picURL = this.src;
                        if (picURL) {
                            const base64Data = await convertImageToBase64(picURL);
                            document.getElementById("item_pic").src = base64Data;
                        }
                    } catch (error) {}
                })();
            });
        }
        // 获取左右按钮
        var leftBtn = document.querySelector(".left");
        var rightBtn = document.querySelector(".right");
        // 为目标div元素添加一个mouseover事件监听器
        leftBtn.addEventListener("mouseover", function (event) {
            const container = document.querySelector("#scroll-content");
            container.scrollBy({ left: -105, behavior: "smooth" });
        });
        rightBtn.addEventListener("mouseover", function (event) {
            const container = document.querySelector("#scroll-content");
            container.scrollBy({ left: 105, behavior: "smooth" });
        });
        leftBtn.addEventListener("click", function (event) {
            const container = document.querySelector("#scroll-content");
            container.scrollBy({ left: -105, behavior: "smooth" });
        });
        rightBtn.addEventListener("click", function (event) {
            const container = document.querySelector("#scroll-content");
            container.scrollBy({ left: 105, behavior: "smooth" });
        });
    }
    // 加载图片资源
    (async () => {
        try {
            var picURL = content.picture;
            if (picURL) {
                const base64Data = await convertImageToBase64(picURL);
                document.getElementById("item_pic").src = base64Data;
                if (imageUrls != null && imageUrls.length == 0) {
                    document.getElementById("item_pic_url").src = picURL;
                } else {
                    document.getElementById("item_pic_url").src = imageUrls.join(",");
                }
            }
        } catch (error) {}
    })();
    document.getElementById("btn-submit").addEventListener("click", postData);
});
